package com.nsgf.library.ui.page.manager;

import static com.nsgf.library.photopicker.PhotoPicker.KEY_SELECTED_PHOTOS;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.kunminx.architecture.ui.page.DataBindingConfig;
import com.kunminx.architecture.ui.state.State;
import com.nsgf.library.BR;
import com.nsgf.library.R;
import com.nsgf.library.data.bean.UserInfo;
import com.nsgf.library.data.bean.WorkOrderBean;
import com.nsgf.library.data.bean.WorkOrderDetailBean;
import com.nsgf.library.data.repository.DataRepository;
import com.nsgf.library.data.response.DataResult;
import com.nsgf.library.data.response.ResponseStatus;
import com.nsgf.library.databinding.ActivityNsgfCreateWorkBinding;
import com.nsgf.library.domain.request.AccountRequester;
import com.nsgf.library.matisse.Matisse;
import com.nsgf.library.photopicker.PhotoPicker;
import com.nsgf.library.photopicker.widget.MultiPickResultView;
import com.nsgf.library.ui.page.BaseActivity;
import com.nsgf.library.ui.page.StateHolder;
import com.nsgf.library.utils.Kits;
import com.nsgf.library.utils.StringUtil;
import com.nsgf.library.utils.ToastUtils;
import com.nsgf.library.widget.prckerview.OptionsPickerView;
import com.nsgf.library.widget.prckerview.TimePickerView;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import io.reactivex.disposables.Disposable;


/**
 * 创建工单
 */
public class WorkCreateActivity extends BaseActivity {

    private CreateWorkStates mStates;

    private ActivityNsgfCreateWorkBinding mBinding;

    private int index = 0;//当前工单类型索引

    final ArrayList<String> list = new ArrayList<>();

    private AccountRequester mAccountRequester;

    WorkOrderBean item;

    @Override
    protected void initViewModel() {
        mStates = new CreateWorkStates();
        mAccountRequester = new AccountRequester();
    }

    @Override
    protected DataBindingConfig getDataBindingConfig() {
        return new DataBindingConfig(R.layout.activity_nsgf_create_work, BR.vm, mStates)
                .addBindingParam(BR.click, new ClickProxy());
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getLifecycle().addObserver(mAccountRequester);
        mBinding = (ActivityNsgfCreateWorkBinding) getBinding();
        item = (WorkOrderBean) getIntent().getSerializableExtra("info");


        list.add("险情上报");
        list.add("违法行为上报");
        list.add("设备巡检");


        if (null == item) {
            mStates.titleBar.set("创建工单");

            index = getIntent().getIntExtra("index", -1);
            if (index != -1) {
                mStates.screenType.set(list.get(index));
            }
            mBinding.multiPickResultView.init(this, MultiPickResultView.ACTION_SELECT, new ArrayList<>(), 9);
        } else {
            mStates.titleBar.set(getIntent().getStringExtra("title"));
            mAccountRequester.workOrderDetail(item.getOrderCode(), String.valueOf(item.getWorkOrderSource()));
            mAccountRequester.getWorkOrderDetailResult().observe(this, new Observer<ResponseStatus<WorkOrderBean>>() {
                @Override
                public void onChanged(ResponseStatus<WorkOrderBean> workOrderBeanResponseStatus) {
                    if (workOrderBeanResponseStatus.getResponseCode() == 200) {
                        mStates.taskName.set(item.getTaskName());
                        mStates.taskTime.set(workOrderBeanResponseStatus.getData().getReportDate());
                        mStates.taskLocal.set(workOrderBeanResponseStatus.getData().getPlace());
                        mStates.problemDesc.set(workOrderBeanResponseStatus.getData().getProblemDescription());
                        mStates.disposeType.set(workOrderBeanResponseStatus.getData().getDisposeType());
                        mStates.screenType.set(item.getWorkOrderSourceSrc());
                        mBinding.multiPickResultView.init(WorkCreateActivity.this, MultiPickResultView.ACTION_ONLY_SHOW, (ArrayList<WorkOrderDetailBean.FileDto>) workOrderBeanResponseStatus.getData().getImageUrls(), 3);
                    }
                }
            });
        }

        mBinding.etNsgfManagerAbnormalDescribe.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                // 当文本改变时更新长度显示
                int length = charSequence.length();
                mBinding.textView.setText(getString(R.string.Input_quantity, length));
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {

            if (PhotoPicker.REQUEST_CODE == requestCode) {
                ArrayList<WorkOrderDetailBean.FileDto> photos = new ArrayList<>();
                for (String src : Matisse.obtainPathResult(data)) {
                    WorkOrderDetailBean.FileDto dto = new WorkOrderDetailBean.FileDto();
                    dto.setFilePath(src);
                    photos.add(dto);
                }
                data.putExtra(KEY_SELECTED_PHOTOS, photos);
                mBinding.multiPickResultView.onActivityResult(requestCode, resultCode, data);
            }
        }
    }

    public static class CreateWorkStates extends StateHolder {

        public final State<String> screenType = new State<>("");//工单类型
        public final State<String> taskTime = new State<>("");//发送时间
        public final State<String> taskName = new State<>("");//任务名称
        public final State<String> taskLocal = new State<>("");//发生地点
        public final State<String> problemDesc = new State<>("");//问题描述
        public final State<String> disposeType = new State<>("");//问题描述

    }

    List<WorkOrderDetailBean.FileDto> fileDto = new ArrayList<>();//待上传的图片


    //illegal：违法行为上报
    //danger：险情上报
    //inspection：设备巡检
    public JsonObject getRequesterParams() {
        JsonObject params = new JsonObject();
        params.addProperty("projectCode", UserInfo.getInstance().getProjectCode());
        params.addProperty("reportDate", mStates.taskTime.get());
        params.addProperty("taskName", mStates.taskName.get());
        params.addProperty("place", mStates.taskLocal.get());
        switch (index) {
            case 0:
                params.addProperty("type", "danger");
                break;
            case 1:
                params.addProperty("type", "illegal");
                break;
            case 2:
                params.addProperty("type", "inspection");
                break;
        }
        params.addProperty("problemDescription", mStates.problemDesc.get());

        JsonArray photos = new JsonArray();
        for (WorkOrderDetailBean.FileDto file : fileDto) {
            JsonObject jsonObject = new JsonObject();
            jsonObject.addProperty("fileName", file.getFileName());
            jsonObject.addProperty("filePath", file.getFilePath());
            jsonObject.addProperty("fileSize", file.getFileSize());
            jsonObject.addProperty("isDelete", file.getIsDelete());
            photos.add(jsonObject);

        }
        params.add("photos", photos);
        return params;
    }


    public class ClickProxy {

        public void cancel() {

        }

        public void close() {
        }

        public void submit() {
            if (StringUtil.isEmpty(mStates.screenType.get())) {
                showToast("请选择工单类型");
                return;
            } else if (StringUtil.isEmpty(mStates.taskTime.get())) {
                showToast("请选择发生时间");
                return;
            } else if (StringUtil.isEmpty(mStates.taskName.get())) {
                showToast("请输入任务名称");
                return;
            } else if (StringUtil.isEmpty(mStates.taskLocal.get())) {
                showToast("请输入发生地点");
                return;
            } else if (StringUtil.isEmpty(mStates.problemDesc.get())) {
                showToast("请输入问题描述");
                return;
            } else if (mBinding.multiPickResultView.getPhotos().isEmpty()) {
                showToast("请上传问题图片");
                return;
            }

            fileDto.clear();
            getController().displayLoading();
            for (WorkOrderDetailBean.FileDto path : mBinding.multiPickResultView.getPhotos()) {
                DataRepository.getInstance().uploadFile(path.getFilePath()).subscribe(new io.reactivex.Observer<DataResult<ResponseStatus<WorkOrderDetailBean.FileDto>>>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onNext(DataResult<ResponseStatus<WorkOrderDetailBean.FileDto>> dataResult) {

                        if (dataResult.getResponseStatus().isSuccess()) {
                            if (200 == dataResult.getResult().getResponseCode()) {
                                fileDto.add(dataResult.getResult().getData());
                                if (mBinding.multiPickResultView.getPhotos().size() == fileDto.size()) {

                                    mAccountRequester.setCreateWord(getRequesterParams());
                                    mAccountRequester.getSrcSuccess().observe(WorkCreateActivity.this, new Observer<ResponseStatus<String>>() {
                                        @Override
                                        public void onChanged(ResponseStatus<String> responseStatus) {
                                            if (responseStatus.getResponseCode() == 200) {
                                                showToast("创建成功");
                                                finish();
                                            } else
                                                showToast(responseStatus.getMsg());
                                        }
                                    });
                                }

                            } else {
                                ToastUtils.showShortToast(dataResult.getResult().getMsg());
                            }

                        } else {
                            getController().dismissLoading();
                            Error(dataResult.getResponseStatus().getE());
                        }

                    }

                    @Override
                    public void onError(Throwable e) {
                        getController().dismissLoading();

                    }

                    @Override
                    public void onComplete() {
                        getController().dismissLoading();
                    }
                });
            }

        }


        public void screenType() {
            OptionsPickerView<String> mOptionsPickerView = new OptionsPickerView.Builder(WorkCreateActivity.this, new OptionsPickerView.OnOptionsSelectListener() {
                @Override
                public void onOptionsSelect(int options1, int options2, int options3, View v) {
                    mStates.screenType.set(list.get(options1));
                    index = options1;
                    mStates.taskName.set(mStates.screenType.get() + mStates.taskTime.get());
                }
            }).build();
            mOptionsPickerView.setPicker(list);
            mOptionsPickerView.setSelectOptions(index > -1 ? index : 0);
            mOptionsPickerView.show();
        }

        public void screenTime() {

            boolean[] type = new boolean[]{true, true, true, true, true, true};//显示类型 默认全部显示

            TimePickerView mTimePickerView = new TimePickerView.Builder(WorkCreateActivity.this, new TimePickerView.OnTimeSelectListener() {
                @Override
                public void onTimeSelect(Date date, View v) {
                    mStates.taskTime.set(Kits.Date.getYmdhmss(date.getTime()));
                    mStates.taskName.set(mStates.screenType.get() + mStates.taskTime.get());
                }
            }).isCyclic(false)
                    .setRangDate(null, Calendar.getInstance())
                    .setType(type)
                    .setDate(Calendar.getInstance())
                    .build();

            mTimePickerView.show();

        }

    }
}
